const express = require('express');
const router = express.Router();
const Friend = require('../models/Friend');
const User = require('../models/User');
const { authenticateToken } = require('../middleware/auth');

// 所有好友相关接口都需要认证
router.use(authenticateToken);
console.log('friends接口验证完成');
/**
 * 获取好友列表
 * GET /friends
 */
router.get('/', async (req, res) => {
  try {
    console.log(`[${new Date().toISOString()}] 获取好友列表请求:`, {
      userId: req.user.userId,
      ip: req.ip || req.connection.remoteAddress
    });

    const friends = await Friend.getFriendsList(req.user.userId);
    
    res.json({
      code: 200,
      message: '获取好友列表成功',
      data: {
        friends: friends,
        total: friends.length
      }
    });
  } catch (error) {
    console.error('获取好友列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取好友列表失败',
      data: null
    });
  }
});

/**
 * 根据邮箱搜索用户
 * GET /friends/search?email=xxx
 */
router.get('/search', async (req, res) => {
  try {
    const { email } = req.query;
    
    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '请提供要搜索的邮箱地址',
        data: null
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: '邮箱格式不正确',
        data: null
      });
    }

    console.log(`[${new Date().toISOString()}] 搜索用户请求:`, {
      userId: req.user.userId,
      searchEmail: email,
      ip: req.ip || req.connection.remoteAddress
    });

    const user = await Friend.searchUserByEmail(email, req.user.userId);
    
    if (!user) {
      return res.json({
        code: 404,
        message: '未找到该用户',
        data: null
      });
    }

    // 检查是否已经是好友
    const isFriend = await Friend.isFriend(req.user.userId, user.userId);
    
    res.json({
      code: 200,
      message: '搜索用户成功',
      data: {
        user: {
          ...user,
          isFriend: isFriend
        }
      }
    });
  } catch (error) {
    console.error('搜索用户失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '搜索用户失败',
      data: null
    });
  }
});

/**
 * 添加好友
 * POST /friends
 * Body: { "email": "friend@example.com" }
 */
router.post('/', async (req, res) => {
  try {
    const { email } = req.body;
    
    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '请提供好友邮箱地址',
        data: null
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: '邮箱格式不正确',
        data: null
      });
    }

    console.log(`[${new Date().toISOString()}] 添加好友请求:`, {
      userId: req.user.userId,
      friendEmail: email,
      ip: req.ip || req.connection.remoteAddress
    });

    // 查找要添加的用户
    const friendUser = await Friend.searchUserByEmail(email, req.user.userId);
    if (!friendUser) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }

    // 添加好友
    const result = await Friend.addFriend(req.user.userId, friendUser.userId);
    
    res.json({
      code: 200,
      message: result.message,
      data: {
        friend: friendUser
      }
    });
  } catch (error) {
    console.error('添加好友失败:', error);
    
    // 根据错误类型返回不同的状态码
    let statusCode = 500;
    if (error.message === '不能添加自己为好友' || error.message === '已经是好友关系') {
      statusCode = 400;
    }
    
    res.status(statusCode).json({
      code: statusCode,
      message: error.message || '添加好友失败',
      data: null
    });
  }
});

/**
 * 删除好友
 * DELETE /friends
 * Body: { "email": "friend@example.com" }
 */
router.delete('/', async (req, res) => {
  try {
    const { email } = req.body;
    
    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '请提供要删除的好友邮箱地址',
        data: null
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: '邮箱格式不正确',
        data: null
      });
    }

    console.log(`[${new Date().toISOString()}] 删除好友请求:`, {
      userId: req.user.userId,
      friendEmail: email,
      ip: req.ip || req.connection.remoteAddress
    });

    // 查找要删除的用户
    const friendUser = await Friend.searchUserByEmail(email, req.user.userId);
    if (!friendUser) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }

    // 删除好友
    const result = await Friend.removeFriend(req.user.userId, friendUser.userId);
    
    res.json({
      code: 200,
      message: result.message,
      data: null
    });
  } catch (error) {
    console.error('删除好友失败:', error);
    
    // 根据错误类型返回不同的状态码
    let statusCode = 500;
    if (error.message === '不是好友关系') {
      statusCode = 400;
    }
    
    res.status(statusCode).json({
      code: statusCode,
      message: error.message || '删除好友失败',
      data: null
    });
  }
});

/**
 * 发送好友申请
 * POST /friends/request
 * Body: { "email": "friend@example.com", "message": "申请消息" }
 */
router.post('/request', async (req, res) => {
  try {
    const { email, message = '' } = req.body;
    
    if (!email) {
      return res.status(400).json({
        code: 400,
        message: '请提供好友邮箱地址',
        data: null
      });
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: '邮箱格式不正确',
        data: null
      });
    }

    console.log(`[${new Date().toISOString()}] 发送好友申请请求:`, {
      fromUserId: req.user.userId,
      toUserEmail: email,
      ip: req.ip || req.connection.remoteAddress
    });

    // 查找目标用户
    const targetUser = await Friend.searchUserByEmail(email, req.user.userId);
    if (!targetUser) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在',
        data: null
      });
    }

    // 发送好友申请
    const result = await Friend.sendFriendRequest(req.user.userId, targetUser.userId, message);
    
    res.json({
      code: 200,
      message: result.message,
      data: {
        targetUser: {
          userId: targetUser.userId,
          email: targetUser.email,
          nickName: targetUser.nickName,
          avatar: targetUser.avatar
        }
      }
    });
  } catch (error) {
    console.error('发送好友申请失败:', error);
    
    let statusCode = 500;
    if (error.message.includes('不能向自己') || error.message.includes('已经是好友') || error.message.includes('已有待处理')) {
      statusCode = 400;
    }
    
    res.status(statusCode).json({
      code: statusCode,
      message: error.message || '发送好友申请失败',
      data: null
    });
  }
});

/**
 * 获取收到的好友申请列表
 * GET /friends/requests
 */
router.get('/requests', async (req, res) => {
  try {
    console.log(`[${new Date().toISOString()}] 获取好友申请列表请求:`, {
      userId: req.user.userId,
      ip: req.ip || req.connection.remoteAddress
    });

    const requests = await Friend.getReceivedRequests(req.user.userId);
    
    res.json({
      code: 200,
      message: '获取好友申请列表成功',
      data: {
        requests: requests,
        total: requests.length
      }
    });
  } catch (error) {
    console.error('获取好友申请列表失败:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '获取好友申请列表失败',
      data: null
    });
  }
});

/**
 * 处理好友申请（同意/拒绝）
 * PUT /friends/requests/:requestId
 * Body: { "action": 1 } // 1-同意，2-拒绝
 */
router.put('/requests/:requestId', async (req, res) => {
  try {
    const { requestId } = req.params;
    const { action } = req.body;
    
    if (!requestId || !action) {
      return res.status(400).json({
        code: 400,
        message: '请提供申请ID和操作类型',
        data: null
      });
    }

    if (![1, 2].includes(parseInt(action))) {
      return res.status(400).json({
        code: 400,
        message: '操作类型无效，1-同意，2-拒绝',
        data: null
      });
    }

    console.log(`[${new Date().toISOString()}] 处理好友申请请求:`, {
      userId: req.user.userId,
      requestId: requestId,
      action: action,
      ip: req.ip || req.connection.remoteAddress
    });

    const result = await Friend.handleFriendRequest(parseInt(requestId), req.user.userId, parseInt(action));
    
    res.json({
      code: 200,
      message: result.message,
      data: null
    });
  } catch (error) {
    console.error('处理好友申请失败:', error);
    
    let statusCode = 500;
    if (error.message.includes('不存在') || error.message.includes('已被处理')) {
      statusCode = 400;
    }
    
    res.status(statusCode).json({
      code: statusCode,
      message: error.message || '处理好友申请失败',
      data: null
    });
  }
});

module.exports = router;